package com.testing.sunnycommon.controller;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.AppenderBase;
import com.testing.sunnycommon.annotations.SunnyAdvice;
import com.testing.sunnycommon.automation.ApiKeywords;
import com.testing.sunnycommon.automation.WebKeywords;
import com.testing.sunnycommon.automation.model.AutoLog;
import com.testing.sunnycommon.model.Result;
import com.testing.sunnycommon.model.SunnyProject;
import com.testing.sunnycommon.service.SunnyProjectService;
import com.testing.sunnycommon.service.SunnyRunService;
import com.testing.sunnycommon.service.impl.SunnyRunServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Classname RunController
 * @Description 类型说明
 * @Date 2023/5/17 10:52
 * @Created by 特斯汀Roy
 */
@RequestMapping("/run")
@RestController
@Slf4j
public class SunnyRunController {
    @Autowired
    SunnyRunService sunnyRunService;

    @Autowired
    SunnyProjectService sunnyProjectService;

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    private Appender appender;

    @SunnyAdvice("自动化测试执行")
    @GetMapping("/{projectId}")
    public Result runAutomationTest(@PathVariable Long projectId) throws InterruptedException {
        //开始执行自动化测试的时候，打开推送appender
        //只有appender为空的时候，才启动appender，否则多次启动就会输出多次日志
        if (appender == null) {
            setUpLogAppender();
        }
        SunnyProject project = sunnyProjectService.getById(projectId);
        if (project == null) {
            return Result.fail(4000, "无法运行自动化用例", "项目不存在！");
        }
        log.info("【" + project.getName() + "】项目：自动化测试开始执行");
        sunnyRunService.runTest(projectId);
        return Result.success("开始执行项目【" + project.getName() + "】自动化测试", project);
    }


    private void setUpLogAppender() {
        //现场实现一个匿名抽象类用于完成实例化操作。
        this.appender = new AppenderBase<ILoggingEvent>() {
            @Override
            protected void append(ILoggingEvent event) {
                //完整的日志对象
                AutoLog autoLog = new AutoLog(
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(event.getTimeStamp())),
                        event.getThreadName(),
                        event.getLoggerName(),
                        event.getLevel().toString(),
                        event.getFormattedMessage()
                );
                System.out.println("在新的appender中输出日志" + autoLog);
                //推送到订阅地址
                simpMessagingTemplate.convertAndSend("/topic/autoLog", autoLog);
            }
        };

        //创建runController类的logger，并且设置为appender
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger runLogger = loggerContext.getLogger(SunnyRunServiceImpl.class);
        Logger webLogger = loggerContext.getLogger(WebKeywords.class);
        Logger apiLogger = loggerContext.getLogger(ApiKeywords.class);

        webLogger.addAppender(appender);
        apiLogger.addAppender(appender);
        runLogger.addAppender(appender);
        appender.start();
    }

}
